/*
 * @Description: 层级组件
 * @Author: Rfan
 * @Date: 2022-06-21 10:25:48
 * @LastEditTime: 2023-03-01 11:18:59
 */

import { ReactNode, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import { useSize } from 'ahooks';
import { LevelTableContextProvider, useLevelTableContext } from './contexts/LevelTableContext';
import LevelOperate from './componentes/LevelOperate';
import LevelTableList from './componentes/LevelTableList';
import type { IArchiveType, ILevel } from '@/interfaces/archiveType';
import styles from './styles/levelTable.module.scss';

const cx = classNames.bind(styles);

export interface IBaseProp extends IArchiveType, ILevel {
  atName: string;
  archiveTypeId: number;
  fondId: number;
  nodeId?: number;
  param: unknown;
  dbName?: string;
  clear?: boolean;
}

interface ILevelTableProps {
  base: IBaseProp;
  upper?: any;
  fields?: any[];
  selectChange: any;
  fetchMethod: any;
  operates?: ReactNode;
  title?: ReactNode;
  // 是否设置表格高度
  isComputeHeight?: boolean;
  onSelectChange?: any;
  type?: number;
}

const LevelTableComp = (props: ILevelTableProps) => {
  const {
    base,
    upper,
    fields,
    fetchMethod,
    selectChange,
    title,
    operates,
    isComputeHeight,
    onSelectChange,
    type
  } = props;
  const { initInfo, setChangeMethod, selectItems, setListHeight, setComputeHeightMethod } =
    useLevelTableContext();

  const tableWrapRef = useRef(null);
  const tableWrapSize = useSize(tableWrapRef);

  useEffect(() => {
    if (isComputeHeight && tableWrapSize?.height) {
      const operateHeight =
        tableWrapRef.current?.getElementsByClassName(cx('level-operate'))[0]?.clientHeight || 0;
      setListHeight(tableWrapSize.height - operateHeight - 45);
    }
  }, [isComputeHeight, tableWrapSize?.height]);

  useEffect(() => {
    if (base.nodeId || base.atCode) {
      initInfo({ base, upper, fields, fetchMethod });
    }
  }, [base]);

  useEffect(() => {
    if (selectChange) {
      setChangeMethod(selectChange);
    }
  }, [selectChange]);

  useEffect(() => {
    onSelectChange && onSelectChange(selectItems);
  }, [selectItems]);

  useEffect(() => {
    // 考虑到只会有启用的情况，故isComputeHeight为falsy时不更改状态
    isComputeHeight && setComputeHeightMethod(!!isComputeHeight);
  }, [isComputeHeight]);

  return (
    <>
      <div ref={tableWrapRef} className={cx('level-table-wrap')}>
        <LevelOperate title={title} operates={operates} base={base} />
        <LevelTableList type={type} />
      </div>
    </>
  );
};

const LevelTable = (props: ILevelTableProps) => (
  <LevelTableContextProvider>
    <LevelTableComp {...props} />
  </LevelTableContextProvider>
);

export default LevelTable;
